package com.hgw.Demo06_Singleton.type5;

/**
 * Data time:2021/12/11 13:28
 * StudentID:2019112118
 * Author:hgw
 * Description: 双重检查
 */
public class SingletonTest05 {

    public static void main(String[] args) {
        Singleton instance1 = Singleton.getInstance();
        Singleton instance2 = Singleton.getInstance();
        System.out.println(instance1==instance2);
    }

}

class Singleton {
    private static volatile Singleton instance;

    private Singleton(){}

    // 提供一个静态的公有方法，加入双重代码，解决线程安全问题
    public static Singleton getInstance() {
        if (instance == null) {
            synchronized (Singleton.class) {
                if (instance == null) {
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }
}